import { useState, useEffect } from "react";
import { Modal, Alert, Tabs, Form, Select, Switch, Col, Radio, Input, message } from "antd";
import CommonModal from "@/components/CommonModal";
import AntdWrapper from "@/components/AntdWrapper";
import { saveOrUpdateVoiceConfig } from "../service";
import { getExpressRelativePrinter, setExpressRelativePrinter } from "@/utils/authority";
import { getAllPrinter } from "@/utils/print.jsx";
import SubTitle from "@/components/SubTitle";

const SetPrintModal = props => {

	// 从缓存中取出快递和打印机配置数据
	const obj = getExpressRelativePrinter() || {};

	const [form] = Form.useForm();

	const { onCancel, expressList, scanConfig, handleOk } = props;

	const [configObj, setConfigObj] = useState(obj);

	const [open, setOpen] = useState(false);

	const [printList, setPrintList] = useState([]);

	useEffect(() => {
	}, []);

	useEffect(() => {
		setOpen(true);
		getAllPrinter(val => {
			console.log(val, 'val')
			const arr = val.map(v => {
				return {
					label: v,
					value: v
				}
			})
			setPrintList(arr);
			form.setFieldsValue({ 
				...obj,
				sortConfig: scanConfig.configStatus == 'open' ? true : false
			});
		});
	}, [])

	// 设置打印机名称
	const handlePrinterName = (item, name) => {
		console.log(item, 'item')
		setConfigObj({
			...configObj,
			[item.baseExpressName]: name
		});
	};

	const onOk = async () => {
		const val = form.getFieldsValue();
		const params = {
			...scanConfig,
			configStatus: val.sortConfig ? 'open' : 'close'
		}
		const { success, data } = await saveOrUpdateVoiceConfig([params]);
		if(success) {
			message.success('操作成功');
			handleOk(params);
			setExpressRelativePrinter(configObj);
			setOpen(false);
		}
	};

	//点击取消
	const handleCancel = () => {
		setOpen(false);
	}

	//关闭事件
	const afterClose = () => {
		onCancel();
	}

	return (
		<CommonModal title="面单打印配置" afterClose={afterClose} open={open} width="588px" okText="保存" onOk={onOk} onCancel={handleCancel}>
			<Form form={form}>
				<SubTitle wrapStyle={{ marginBottom: '12px' }} symbol as="s2" title="面单发货时机配置" />
				<Form.Item name="sortConfig" valuePropName="checked" style={{ marginBottom: '4px'}} label="同笔订单连续扫码完成才可打单发货：" >
					<Switch />
				</Form.Item>
				<div className="common-color9">注：开启后必须将同一笔订单连续扫码完成才可打单发货，中断后需要重新扫码</div>
				<SubTitle wrapStyle={{ margin: '16px 0 12px' }} symbol as="s2" title="打印机配置" />
				{expressList.map(item => (
					<AntdWrapper key={item.id} label={<div>{item.name}</div>} style={{ width: "100%" }}>
						<Form.Item name={item.baseExpressName}>
							<Select placeholder="请选择打印机" onChange={e => handlePrinterName(item, e)} value={configObj[item]} options={printList}>
							</Select>
						</Form.Item>
					</AntdWrapper>
				))}
			</Form>
		</CommonModal>
	);
};
export default SetPrintModal;
